import oss2
from config import BaseConfig

class AliOssUploader:
    def __init__(self):
        """
        初始化OSS客户端
        """
        auth = oss2.Auth(
            BaseConfig.ALIYUN_OSS_ACCESS_KEY_ID,
            BaseConfig.ALIYUN_OSS_ACCESS_KEY_SECRET
        )
        self.bucket = oss2.Bucket(
            auth,
            BaseConfig.ALIYUN_OSS_ENDPOINT,
            BaseConfig.ALIYUN_OSS_BUCKET_NAME
        )

    def upload_file(self, file_path, object_name):
        """
        上传文件到OSS
        :param file_path: 本地文件路径
        :param object_name: OSS存储路径
        :return: 上传结果
        """
        try:
            self.bucket.put_object_from_file(object_name, file_path)
            return True
        except Exception as e:
            print(f"上传文件失败: {e}")
            return False

    def download_file(self, object_name, file_path):
        """
        从OSS下载文件
        :param object_name: OSS存储路径
        :param file_path: 本地保存路径
        :return: 下载结果
        """
        try:
            self.bucket.get_object_to_file(object_name, file_path)
            return True
        except Exception as e:
            print(f"下载文件失败: {e}")
            return False

    def delete_file(self, object_name):
        """
        从OSS删除文件
        :param object_name: OSS存储路径
        :return: 删除结果
        """
        try:
            self.bucket.delete_object(object_name)
            return True
        except Exception as e:
            print(f"删除文件失败: {e}")
            return False
            
    def get_file_url(self, object_name):
        """
        获取文件访问URL
        :param object_name: OSS存储路径
        :return: 文件访问URL
        """
        try:
            return f"https://{BaseConfig.ALIYUN_OSS_DOMAIN}/{object_name}"
        except Exception as e:
            print(f"获取文件URL失败: {e}")
            return None